package servlets;

import model.Chapter;
import model.Comic;
import model.History;
import model.User;
import net.sf.json.JSONArray;
import services.ChapterServices;
import services.CollectionServices;
import services.ComicServices;
import services.HistoryServices;
import utils.MyJSONUtils;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 访问漫画主页，会先经过这个servlet，再转到jsp显示
 */

@WebServlet(name = "ComicServlet", urlPatterns = "/comic")
public class ComicServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    private ComicServices comicServices;
    private ChapterServices chapterServices;

    public ComicServlet() {
        comicServices = new ComicServices();
        chapterServices = new ChapterServices();
    }

    private void processElement(HttpServletRequest request, HttpServletResponse response, String comicId) {
        //服务创建
        CollectionServices collectionServices = new CollectionServices();
        HistoryServices historyServices = new HistoryServices();


        //获取章节
        List<Chapter> clist = chapterServices.getComicChapterList(comicId);
        JSONArray clistjson = JSONArray.fromObject(clist, MyJSONUtils.jsonConfig);
        //将章节list加入到request中
        request.setAttribute("chapters", clistjson);
        //第一章id，开始阅读按钮用
        request.setAttribute("start_chapterId", clist.get(0).getId());


        //历史记录默认章节id
        request.setAttribute("history_chapterId", 0);

        //收藏数量显示
        int collectCount = collectionServices.getCollectionCount(comicId);
        request.setAttribute("collectCount", collectCount);

        //漫画标签
        request.setAttribute("tags", comicServices.getComicTags(comicId));
        //增加点击量
        comicServices.addComicClick(comicId);

        boolean haveUserCollect = false;//标志用户是否已经收藏过该漫画
        String btn_collect_text = "加入收藏";
        User user = (User) request.getSession().getAttribute("user");
        if (user != null) {
            //用户已经登录
            //
            //收藏相关
            if (collectionServices.isUserHaveCollection(user.getUser_name(), comicId)) {
                //已经收藏过了
                haveUserCollect = true;
                btn_collect_text = "取消收藏";
            }

            //检查用户是否有浏览历史
            History history = historyServices.checkHistory(user.getUser_name(), comicId);
            if (history == null || (history.getChapter_id() == 0)) {
                //添加浏览历史，并且章节为第0章
                historyServices.addHistory(user.getUser_name(), Integer.parseInt(comicId), 0);
            } else {
                //只有一种情况history=null && getChapter_id！=0,表示之前已经阅读到这漫画的某一章节
                int id = history.getChapter_id();
                request.setAttribute("history_chapterId", id);
                request.setAttribute("history_chapter", chapterServices.getChapterDetail(String.valueOf(id)));
            }


        }
        request.setAttribute("haveUserCollect", haveUserCollect);

        //收尾
        collectionServices.finish();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter pw = response.getWriter();
        //获取漫画id
        RequestDispatcher rd = request.getRequestDispatcher("/comic.jsp");
        String comicId = request.getParameter("comicid");

        if (comicId != null && !comicId.equals("")) {
            //漫画服务
            Comic comic = comicServices.getComicDetail(Integer.parseInt(comicId));
            if (comic != null) {
                request.setAttribute("comic", comic);

                processElement(request, response, comicId);

                //转发到显示页面
                rd.forward(request, response);
            } else {
                pw.write("没有这个漫画呦！");
            }
        } else {
            pw.write("出错啦！");
        }
    }
}
